package pers.qianyu.converter;

import com.alibaba.excel.converters.*;
import com.alibaba.excel.enums.*;
import com.alibaba.excel.metadata.*;
import com.alibaba.excel.metadata.property.*;

import java.time.*;
import java.time.format.*;
import java.util.*;

/**
 * LocalDateTime 类型转 String 类型
 *
 * @author mizzle rain
 * @date 2020-10-14 23:45
 */
public class LocalDateTimeStringConverter implements Converter<LocalDateTime> {
    @Override
    public Class supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 导入时使用的，将一个 Excel 对象转换为 Java 对象
     *
     * @param cellData
     * @param excelContentProperty
     * @param globalConfiguration
     * @return
     * @throws Exception
     */
    @Override
    public LocalDateTime convertToJavaData(
            CellData cellData,
            ExcelContentProperty excelContentProperty,
            GlobalConfiguration globalConfiguration) throws Exception {
        return null;
    }

    /**
     * 导出时使用，将 Java 对象转换为 Excel 对象
     *
     * @param localDateTime
     * @param excelContentProperty
     * @param globalConfiguration
     * @return
     * @throws Exception
     */
    @Override
    public CellData convertToExcelData(
            LocalDateTime localDateTime,
            ExcelContentProperty excelContentProperty,
            GlobalConfiguration globalConfiguration) throws Exception {
        if (Objects.isNull(excelContentProperty) ||
                Objects.isNull(excelContentProperty.getDateTimeFormatProperty())) {
            return new CellData(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTime));
        }
        return new CellData(DateTimeFormatter.ofPattern(
                excelContentProperty.getDateTimeFormatProperty()
                        .getFormat()).format(localDateTime));
    }
}
